<template>
  <div>
    <div class="theme-tab-container">
      <a-tabs v-model:activeKey="activeKey" @change="handleTabClick">
        <a-tab-pane v-for="item in tabList" :key="item.id" :tab="item.name">
          <div
            v-if="item.children && item.children.length"
            class="card-box"
            
          >
            <div 
            v-for="(_item, _index) in item.children"
            :key="_index"
              :style="{ background: colorList[_index % colorList.length] }"
              @click="handleTabClick(_item.id)"
              class="card-content"
              >
                {{ _item.name }}
                </div>
          </div>
          <div v-else class="noBox">
            <WalletOutlined class="text-20px mr-10px" />
            <span>没有表单类型</span>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <DynamicTable
      :formProps="formProps"
      auto-height
      :data-request="loadTableData"
      :columns="columns"
      :closable="false"
    >
      <template #toolbar>
        <a-button type="primary" @click="openMenuModal({})"> <PlusOutlined />新增 </a-button>
      </template>
    </DynamicTable>
    <a-config-provider
      :theme="{
        algorithm: theme.defaultAlgorithm,
        token: {
          colorBgBase: '#FFF',
        },
      }"
    >
      <a-drawer
        v-if="showForm"
        @close="handleDrawClose"
        class="formDrawer"
        width="100%"
        height="100%"
        title="表单设计"
        v-model:open="showForm"
        placement="bottom"
        destroyOnClose
      >
        <FormDesigner :value="formValue" :formId="formId"></FormDesigner>
      </a-drawer>
    </a-config-provider>
    <a-config-provider
      :theme="{
        algorithm: theme.defaultAlgorithm,
        token: {
          colorBgBase: '#FFF',
        },
      }"
    >
      <a-drawer
        v-if="showPreview"
        @close="handlePreviewDrawClose"
        title="表单预览"
        width="100%"
        height="95%"
        v-model:open="showPreview"
        placement="bottom"
        destroyOnClose
      >
        <preview :item-list="itemList" :form-conf="formConfPreview"></preview>
      </a-drawer>
    </a-config-provider>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, h } from 'vue';
  import type { LoadDataParams, TableColumn } from '@/components/core/dynamic-table';
  import { useTable } from '@/components/core/dynamic-table';
  import FormDesigner from '@/components/form/formDesigner.vue';
  import preview from '@/components/form/preview.vue';
  import { getFormList, deleteForm } from '@/api/form/index';
  import { formatFormSortTree } from '@/views/form/formSort/columns';
  import {
    DeleteOutlined,
    EyeOutlined,
    SettingOutlined,
    WalletOutlined,
    PlusOutlined,
  } from '@ant-design/icons-vue';
  import { getFormSortList } from '@/api/form/sort';
  import type { SchemaFormProps } from '@/components/core/schema-form';
  import { flatTree } from '@/core/permission/utils';
  import { cloneDeep } from 'lodash-es';
  import type { TreeSelectProps } from 'ant-design-vue';
  import { useFormModal } from '@/hooks/useModal/useFormModal';
  import { useFormSchema } from '@/views/form/list/formSchemas';
  import formConf from '@/components/form/custom/formConf.js';
  import { theme } from 'ant-design-vue';

  defineOptions({
    name: 'FormList',
  });

  const formSortTree = ref<TreeSelectProps['treeData']>([]);

  const formProps = reactive<SchemaFormProps>({
    resetFunc: async () => {
      choosedSort.value = '';
    },
  });

  const formId = ref('');

  const colorList = ['#3D96F9', '#F5B658', '#42DDA9', '#B48BE4', '#C55A5A'];
  const tabList = ref<API.FormSortListResultItem[]>();
  const activeKey = ref('');
  const choosedSort = ref('');

  const handleTabClick = (id) => {
    choosedSort.value = id;
    dynamicTableInstance?.reload();
  };

  const showForm = ref(false);
  const handleDrawClose = () => {
    showForm.value = false;
    dynamicTableInstance?.reload?.();
  };
  const formValue = ref<any>({});

  const itemList = ref<any>([]);
  const formConfPreview = ref<any>({});

  const showPreview = ref(false);
  const handlePreviewDrawClose = () => {
    showPreview.value = false;
  };
  // 获取分类数据
  const loadSortList = async () => {
    const data = await getFormSortList();
    const flatTreeData = flatTree(data.result);
    tabList.value = formatFormSortTree(cloneDeep(flatTreeData), '0') as any;
    formSortTree.value=tabList.value;
    if (tabList.value?.length) {
      activeKey.value = tabList.value[0].id;
    }
    console.log(formSortTree.value,"tabList.value111")
  };
  loadSortList();

  const [showModal] = useFormModal();
  // 达开详情弹窗
  const openMenuModal = async (record: any) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `新增表单`,
        width: 700,
        onFinish: async (values) => {
          console.log({
            ...formConf,
            ...values,
          });
          formValue.value = JSON.stringify({
            config: {
              ...formConf,
              ...values,
            },
            list: [],
          });
          showForm.value = true;
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: useFormSchema(),
      },
    });

    formRef?.updateSchema([
      {
        field: 'formSort',
        componentProps: {
          treeDefaultExpandedKeys: ['0'].concat(record?.keyPath || []),
          treeData: ref([{ id: '0', name: '主目录', children: formSortTree.value }]),
        },
      },
    ]);
    const id = uuidv4();
    formRef?.setFieldsValue({
      formId: id,
    });
    formId.value = id;
  };
  // 编辑
  const handleEdit = (row) => {
    formValue.value = row.form_json;
    showForm.value = true;
  };
  // 预览
  const handlePreview = (row) => {
    const _val = JSON.parse(row.form_json);
    itemList.value = _val.list ?? [];
    formConfPreview.value = _val.config ?? {};
    showPreview.value = true;
  };

  const [DynamicTable, dynamicTableInstance] = useTable();

  const loadTableData = async (params: LoadDataParams) => {
    const data = await getFormList({
      ...params,
      form_type: choosedSort.value,
      pagesize: params.limit,
    });
    return {
      list: data.rows || [],
      pagination: {
        total: data.total,
        size: params.limit,
        page: params.page,
      },
    } as API.TableListResult;
  };

  const handleDeleteForm = async (id) => {
    await deleteForm({ id });
    dynamicTableInstance?.reload();
  };

  const uuidv4 = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  };

  const columns: TableColumn[] = [
    {
      title: '表单名称',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '类别',
      dataIndex: 'formSortName',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '操作',
      width: 320,
      dataIndex: 'ACTION',
      align: 'center',
      actions: ({ record }) => [
        {
          label: '设计',
          icon: h(SettingOutlined),
          onClick: () => {
            handleEdit(record);
            formId.value = record.id;
          },
        },
        {
          label: '预览',
          icon: h(EyeOutlined),
          onClick: () => {
            handlePreview(record);
          },
        },
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => handleDeleteForm(record.id),
          },
        },
      ],
    },
  ];
</script>
<style lang="less" scoped>
  .formDrawer .ant-drawer-body {
    padding: 0 !important;
    overflow: hidden;
  }

  .formDrawer .ant-drawer-header-title {
    flex-direction: row-reverse;
  }

  .formDrawer .action-bar {
    position: fixed;
    top: 10px;
    right: 80px;
    border: none !important;
  }
</style>
<style lang="less" scoped>
  @import '@/styles/navTheme.less';
  @classBacks: theme-tab-container;
  .customSetStyle(@classBacks, background-color, 'content-back');

  .theme-tab-container {
    margin-bottom: 10px;
    padding: 10px 0 20px 16px;
    background-color: #fff;

    .noBox {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100px;
      background: rgba(#000, 0.03);
      font-size: 14px;
    }

    .card-box {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: calc(100vw - 280px);
      overflow: auto;

      .card-content {
        display: inline-block;
        box-sizing: border-box;
        width: 226px;
        height: 100px;
        margin-right: 10px;
        border-radius: 4px;
        color: #fff;
        font-size: 16px;
        line-height: 100px;
        text-align: center;
        cursor: pointer;
        flex-shrink:0;

        &:last-of-type {
          margin-right: 0;
        }

        &:hover,
        &.is-active {
          box-shadow:
            0 2px 7px 0 rgb(0 0 0 / 32%),
            0 1px 4px 0 rgb(183 183 183 / 6%);
        }
      }
    }
  }
</style>
